package com.asset.dispoal.file.agreementCaseData.service.commom;

import com.asset.dispoal.business.bsAgreement.dto.AgreementRequest;
import com.asset.dispoal.file.agreementCaseData.domain.db.mapper.CaseMapper;
import com.asset.dispoal.file.agreementCaseData.domain.dto.BsDataDetailExportCaseTemplate;
import com.asset.dispoal.file.agreementCaseData.dto.AgreementExportRequest;
import com.asset.dispoal.file.common.ExcelExport;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.core.spring.util.DataUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author qr
 * @date 2022/5/6$
 */
@Component
public class ExportCaseExcelCommand implements BaseCommand<Map<String, Object>, Result> {

    @Autowired
    CaseMapper agreementMapper;


    @SneakyThrows
    @Override
    public Result execute(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        AgreementExportRequest agreementRequest = (AgreementExportRequest) map.get("agreementRequest");
        AgreementRequest queryParam = DataUtil.copyTo(agreementRequest, AgreementRequest.class);
        String permission = (String) GlobalHeaderThreadLocal.get().getExtraMap().get("permission");
        queryParam.setPermission(permission);
        List<BsDataDetailExportCaseTemplate> bsDataDetailExportTemplates = agreementMapper.queryCaseTemplate(queryParam);
        if (CollectionUtil.isEmpty(bsDataDetailExportTemplates)) {
            throw new BusinessException("数据错误");
        }
        ExcelExport.export(response, agreementRequest.getFileName(), bsDataDetailExportTemplates, BsDataDetailExportCaseTemplate.class);
        return Result.ok();
    }
}
